<?php
/** 防止非法引用 */
if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

include_once dirname(__FILE__).'/class/util.class.php';

class plugin_iwenwen {
	
	var $interval = 43200;
	
	function plugin_iwenwen(){
		include_once DISCUZ_ROOT.'./source/discuz_version.php';
		if(strcmp(DISCUZ_VERSION,'X2.5')<0){
			define('USE_DB_SQL',true);
		}
	}
	function init() {
		
	}
	
	function common(){
		global $_G;
	}
	
	/**
	 * 删回贴，sql使用silent方式，即使表格不存在也不引入错误
	 * @param unknown_type $params
	 */
	public function deletepost($params) {
		$pids = $params['param'][0];
		$idtype = $params['param'][1];
		$step = $params['step'];

		if($step == 'delete' && $idtype == 'pid' && is_array($pids)) {
			include_once dirname(__FILE__).'/class/api.class.php';
			$api = new IwenwenApi();
			if(class_exists('C')){
				$query = DB::query("select * from ".DB::table('iwenwen_backflow')." where pid in (".implode(',',$pids).")",null,'SILENT');
				while($row = DB::fetch($query)) {
					$api->deletewenwen($row['qid'],$row['answerid']);
				}
				DB::query("delete from ".DB::table('iwenwen_backflow')." where pid in (".implode(',',$pids).")",null,'SILENT');
			}
			else{
				$query = DB::query("select * from ".DB::table('iwenwen_backflow')." where pid in (".implode(',',$pids).")",'SILENT');
				while($row = DB::fetch($query)) {
					$api->deletewenwen($row['qid'],$row['answerid']);
				}
				DB::query("delete from ".DB::table('iwenwen_backflow')." where pid in (".implode(',',$pids).")",'SILENT');
			}
		}
	}
	
	/**
	 * 删主贴，sql使用silent方式，即使表格不存在也不引入错误
	 * @param unknown_type $params
	 */
	public function deletethread($params) {
		$tids = $params['param'][0];
		$step = $params['step'];

		if($step == 'delete' && is_array($tids)) {
			include_once dirname(__FILE__).'/class/api.class.php';
			$api = new IwenwenApi();
			if(class_exists('C')){
				$query = DB::query("select * from ".DB::table('iwenwen_backflow')." where answerid=0 and tid in (".implode(',',$tids).")",null,true);
				while($row = DB::fetch($query)) {
					$api->deletewenwen($row['qid']);
				}
				DB::query("delete from ".DB::table('iwenwen_backflow')." where answerid=0 and tid in (".implode(',',$tids).")",null,true);
			}
			else{
				$query = DB::query("select * from ".DB::table('iwenwen_backflow')." where answerid=0 and tid in (".implode(',',$tids).")",'SILENT');
				while($row = DB::fetch($query)) {
					$api->deletewenwen($row['qid']);
				}
				DB::query("delete from ".DB::table('iwenwen_backflow')." where answerid=0 and tid in (".implode(',',$tids).")",'SILENT');
			}
			
		}
	}
	
}

class plugin_iwenwen_forum extends plugin_iwenwen {
	
	var $adnums = array();
	
	function plugin_iwenwen_forum(){
		
	}

	/**
	 * 在页码逻辑后，处理$postlist变量，iwenwen回流的帖子设置头像，不显示ip
	 */
	function viewthread_bottom_output() {
		global $_G,$postlist, $page;
		$pids = array();
		$i = 0;
		$tid = '';
		foreach($postlist as $pid => $post){
			if(empty($tid)){
				$tid = $post['tid'];
			}
			//if($post['anonymous'] && getstatus($post['status'], 5)) {
			if($post['anonymous']) {
				$pids[$pid] = $i;
			}
			$i++; //记录每个帖子的顺序1-10，在广告代码时作为判断
		}
		/**
		* 发帖时，状态不记为5，此处查找所有贴子，将出现在iwenwen_backflow中的帖子状态设为5。不影响qqconnect插件的执行
		*/
		if(!empty($pids)){
			if(class_exists('C')){
				$query = DB::query("select * from ".DB::table('iwenwen_backflow')." where tid=$tid and pid in (".implode(',',array_keys($pids)).")",null,true);
			}
			else{
				$query = DB::query("select * from ".DB::table('iwenwen_backflow')." where tid=$tid and pid in (".implode(',',array_keys($pids)).")",'SILENT');
			}
			while($row = DB::fetch($query)) {
				$pid = $row['pid'];				
				$postlist[$pid]['useip'] = '';
				$postlist[$pid]['status'] = setstatus(5,1,$postlist[$pid]['status']);
				$postlist[$pid]['avatar'] = '<img src="source/plugin/iwenwen/template/avatar.jpg"/>';
				$this->adnums[] = $pids[$pid];
			}
		}
	}
	
	/**
	 * 统计回流问题的回答数,IwenwenApi
	 * 在iwenwen插件中，不会调用showmessage方法，不会触发此函数。回答的答案不会进入此流程
	 * @param unknown_type $params
	 */
	public function post_message($params) {
		global $_G;
		
		//post_newthread_succeed 新帖
		//post_reply_succeed回帖
		if(isset($params['param'])) $params = $params['param'];
		/**通过问问到达站点的问题与答案，没有显示message提示，不会触发此方法 **/
		include_once dirname(__FILE__).'/class/api.class.php';
		if($params[0]=='post_reply_succeed'){ // 发起新回帖成功时触发
			$tid = $params[2]['tid'];$pid=$params[2]['pid'];
			// 判断主贴是否来源iwenwen回流
			$isbackflow = DB::fetch_first("select * from ".DB::table('iwenwen_backflow')." where `tid`='".$tid."' and `answerid`=0 order by sync_time desc",null,true);
			if(!empty($isbackflow)){ // 来源iwenwen的回流贴，统计回答数，提交回答内容至问问
				$curr_date = date('Ymd');
				$hasone = DB::fetch_first("select * from ".DB::table('iwenwen_answers')." where `date`='".$curr_date."'",null,true);
				if(!empty($hasone)){
					DB::query("update ".DB::table('iwenwen_answers')." set post_num=post_num+1 where `date`='".$curr_date."'",null,true);
				}
				else{
					DB::query("insert into ".DB::table('iwenwen_answers')." (`date`,`post_num`) values('".$curr_date."',1)",null,true);
				}
				
				if($isbackflow['qid']){
					$post = DB::fetch_first("select * from ".DB::table('forum_post')." p where  p.`pid`='".$pid."' and p.`tid`='".$tid."'",null,true);
					if(!empty($post)){
						require_once libfile('function/discuzcode');
						$message = discuzcode($post['message'], $post['smileyoff'], $post['bbcodeoff'], $post['htmlon'] & 1, $_G['forum']['allowsmilies'], 1, ($_G['forum']['allowimgcode'] && $_G['setting']['showimages'] ? 1 : 0), $_G['forum']['allowhtml'], ($_G['forum']['jammer'] && $post['authorid'] != $_G['uid'] ? 1 : 0), 0, $post['authorid'], $_G['cache']['usergroups'][$post['groupid']]['allowmediacode'] && $_G['forum']['allowmediacode'], $post['pid'], $_G['setting']['lazyload'], $post['dbdateline']);
						$api = new IwenwenApi();
						$host_url = str_replace('\\','/',$_SERVER['SERVER_NAME'].dirname($_SERVER['SCRIPT_NAME']));
						$api->sendNewAnswer(array(
								'questionid' => $isbackflow['qid'],
								'content' => $message,
								'tid' => $tid,
								'pid' => $pid,
								'anonymous' => true,
								'dzType' => 1,
								'url' => 'http://'.$host_url.'/forum.php?mod=redirect&goto=findpost&ptid='.$tid.'&pid='.$pid,
						));
					}
				}
			}
			else{
                #及时同步本站产生的回帖
                if ($_G['setting']['iwenwen_question_sync_flag'] == '1') {
                    #查数据库
                    $sql = "select * from ". DB::table('forum_post') . " where `tid`='".$tid."' and `pid`='".$pid."'";
                    $postdata = DB::fetch_first($sql);
                    $sql = "select * from ". DB::table('forum_thread') . " where `tid`='".$tid."'";
                    $threaddata = DB::fetch_first($sql);
                    if (!empty($postdata) && !empty($threaddata)) {
                        $iwenwenUtil = new IwenwenUtil();
                        #提交post请求给开发平台接口
                        $pdata = array();
                        #discuz版本号
                        $pdata['VR'] = $_G['setting']['version'];
                        #站点ID
                        $pdata['ID'] = $_G['setting']['my_siteid'];
                        #是否是主贴
                        $pdata['TY'] = '0';
                        #帖子ID
                        $pdata['TD'] = strval($postdata['pid']);
                        #主题ID
                        $pdata['ZD'] = strval($postdata['tid']);
                        #板块ID
                        $pdata['BD'] = strval($postdata['fid']);
                        #作者ID
                        $pdata['AD'] = strval($postdata['authorid']);
                        #作者名称
                        $pdata['AU'] = $postdata['author'];
                        #发帖IP
                        $pdata['IP'] = strval(sprintf('%u', ip2long($postdata['useip'])));
                        #帖子标题
                        $pdata['TI'] = strip_tags($threaddata['subject']);
                        #帖子内容
                        $pdata['TX'] = $iwenwenUtil->strip_simple('img', $postdata['message']);
                        #发表时间
                        $pdata['NA'] = strval($postdata['dateline']);
                        /*帖子状态-开始*/
                        $np = 0;
                        #是否匿名
                        $np = intval($postdata['anonymous']);
                        #是否有附件
                        $np = intval($postdata['attachment']) * 2 + $np;
                        #是否高亮
                        $np = intval($threaddata['highlight']) * 8 + $np;
                        #是否群组
                        $np = intval($threaddata['isgroup']) * 16 + $np;
                        $pdata['NP'] = strval($np);
                        /*帖子状态-结束*/
                        $jsondata = CJSON::encode($pdata);

                        #给接口发post请求
                        $api = new IwenwenApi();
                        $result = $api->postMessageWithJson($jsondata);
                    }
                }
			}
		}
		elseif($params[0]=='post_newthread_succeed'){ // 新主题贴发表成功时触发
			$tid = $params[2]['tid'];$pid=$params[2]['pid'];
			// 判断主贴是否来源iwenwen回流
			$isbackflow = DB::fetch_first("select * from ".DB::table('iwenwen_backflow')." where `tid`='".$tid."' and `answerid`=0 order by sync_time desc",null,true);
			if(!empty($isbackflow)){
			    // 来源iwenwen的答案回流数据
			}
			else{
                //本站产生的数据，通过iwenwen接口提交至问问开放平台
                if ($_G['setting']['iwenwen_question_sync_flag'] == '1') {

                    #查数据库
                    $sql = "select * from ". DB::table('forum_post') . " where `tid`='".$tid."' and `pid`='".$pid."'";
                    $postdata = DB::fetch_first($sql);
                    $sql = "select * from ". DB::table('forum_thread') . " where `tid`='".$tid."'";
                    $threaddata = DB::fetch_first($sql);
                    if (!empty($postdata) && !empty($threaddata)) {
                        $iwenwenUtil = new IwenwenUtil();
                        #提交post请求给开发平台接口
                        $pdata = array();

                        #discuz版本号
                        $pdata['VR'] = $_G['setting']['version'];
                        #站点ID
                        $pdata['ID'] = $_G['setting']['my_siteid'];
                        #是否是主贴
                        $pdata['TY'] = '1';
                        #帖子ID
                        $pdata['TD'] = strval($postdata['pid']);
                        #主题ID
                        $pdata['ZD'] = strval($postdata['tid']);
                        #板块ID
                        $pdata['BD'] = strval($postdata['fid']);
                        #作者ID
                        $pdata['AD'] = strval($postdata['authorid']);
                        #作者名称
                        $pdata['AU'] = $postdata['author'];
                        #发帖IP
                        $pdata['IP'] = strval(sprintf('%u', ip2long($postdata['useip'])));
                        #帖子标题
                        $pdata['TI'] = strip_tags($threaddata['subject']);
                        #帖子内容
                        $pdata['TX'] = $iwenwenUtil->strip_simple('img', $postdata['message']);
                        #发表时间
                        $pdata['NA'] = strval($postdata['dateline']);
                        /*帖子状态*/
                        $np = 0;
                        #是否匿名
                        $np = intval($postdata['anonymous']);
                        #是否有附件
                        $np = intval($postdata['attachment']) * 2 + $np;
                        #是否是主题贴
                        $np = 4 + $np;
                        #是否高亮
                        $np = intval($threaddata['highlight']) * 8 + $np;
                        #是否群组
                        $np = intval($threaddata['isgroup']) * 16 + $np;
                        $pdata['NP'] = strval($np);
                        /*帖子状态*/
                        $jsondata = CJSON::encode($pdata);
                        $api = new IwenwenApi();
                        $result = $api->postMessageWithJson($jsondata);
                    }
                }
			}
		}
	}
}
